﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace PKSMonitorNew
{
    using GraphLib;
    public partial class Form3 : Form
    {
        private int NumGraphs = 1;
        private String CurExample = "ANIMATED_AUTO";
        private String CurColorSchema = "BLACK";
        private PrecisionTimer.Timer mTimer = null;
        private DateTime lastTimerTick = DateTime.Now;

        private static float[,] Lead;
        //private static int FPL;
        private static int CPL;
        //private static int LeadNum;
        private static int NSample = 500;  // 2 seconds; 125 samples/sec;

        private float ymin = (float)-1.5, ymax = (float)1.5;
        private int graphSelected;


        public Form3(MainForm form1)
        {
            InitializeComponent();
            mainForm = form1;

            Lead = new float[6, NSample];

            //FPL = -1;
            CPL = 0;
            //LeadNum = 0;

            display2.Smoothing = System.Drawing.Drawing2D.SmoothingMode.None;
            graphSelected = int.Parse(cbGraphNum.SelectedIndex.ToString());

            CalcDataGraphs();
            display2.Refresh();
            GetData();
            //UpdateGraphCountMenu();

            //UpdateColorSchemaMenu();
            mTimer = new PrecisionTimer.Timer();
            mTimer.Period = 50;                         // 20 fps
            mTimer.Tick += new EventHandler(OnTimerTick);
            lastTimerTick = DateTime.Now;
            mTimer.Start();
            //timer1.Enabled = true;
        }

        private void OnTimerTick(object sender, EventArgs e)
        {
            if (CurExample == "ANIMATED_AUTO")
            {
                try
                {
                    //TimeSpan dt = DateTime.Now - lastTimerTick;

                    //for (int j = 0; j < NumGraphs; j++)
                    //{
                        //CalcSinusFunction_3(display.DataSources[j], j, (float)dt.TotalMilliseconds);
                        CalcSinusFunction_3(display2.DataSources[0], graphSelected, 0);
                    //}

                    this.Invoke(new MethodInvoker(RefreshGraph));
                }
                catch (ObjectDisposedException ex)
                {
                     WriteLog("OnTimerTick Zoom: " + ex.Message.ToString());// we get this on closing of form
                }
                catch (Exception ex)
                {
                    WriteLog("Zoom:exception invoking refreshgraph(): " + ex.Message);
                }


            }
        }

        public static void WriteLog(string str)
        {
            string FileName = Application.StartupPath + @"\Log\ErrorLog_" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt";
            string Dir = Application.StartupPath + @"\Log";
            if (!Directory.Exists(Dir))
            {
                Directory.CreateDirectory(Dir);
            }
            else
            {
                using (StreamWriter sw = new StreamWriter(FileName, true))
                {
                    sw.WriteLine("Record Time: " + DateTime.Now);
                    sw.WriteLine(str);
                    sw.WriteLine("");
                }
            }
        }

        private MainForm mainForm;
        private void GetData()
        {
            Lead = mainForm.GraphData; ;
        }

        private void RefreshGraph()
        {
            display2.Refresh();
        }

        protected void CalcSinusFunction_3(DataSource ds, int idx, float time)
        {
            int index = CPL;
            cPoint[] src = ds.Samples;
          
            for (int i = 0; i < src.Length; i++)
            {
                src[i].x = i;
                src[i].y = Lead[idx, index++];

                index = index % NSample;
            }
            if (idx == 0)
                CPL = index;
        }

        private void ApplyColorSchema()
        {
            switch (CurColorSchema)
            {
                case "DARK_GREEN":
                    {
                        Color[] cols = { Color.FromArgb(0,255,0), 
                                         Color.FromArgb(0,255,0),
                                         Color.FromArgb(0,255,0), 
                                         Color.FromArgb(0,255,0), 
                                         Color.FromArgb(0,255,0) ,
                                         Color.FromArgb(0,255,0),                              
                                         Color.FromArgb(0,255,0) };

                        for (int j = 0; j < NumGraphs; j++)
                        {
                            display2.DataSources[j].GraphColor = cols[j % 7];
                        }

                        display2.BackgroundColorTop = Color.FromArgb(0, 64, 0);
                        display2.BackgroundColorBot = Color.FromArgb(0, 64, 0);
                        display2.SolidGridColor = Color.FromArgb(0, 128, 0);
                        display2.DashedGridColor = Color.FromArgb(0, 128, 0);
                    }
                    break;
                case "WHITE":
                    {
                        Color[] cols = { Color.DarkRed, 
                                         Color.DarkSlateGray,
                                         Color.DarkCyan, 
                                         Color.DarkGreen, 
                                         Color.DarkBlue ,
                                         Color.DarkMagenta,                              
                                         Color.DeepPink };

                        for (int j = 0; j < NumGraphs; j++)
                        {
                            display2.DataSources[j].GraphColor = cols[j % 7];
                        }

                        display2.BackgroundColorTop = Color.White;
                        display2.BackgroundColorBot = Color.White;
                        display2.SolidGridColor = Color.LightGray;
                        display2.DashedGridColor = Color.LightGray;
                    }
                    break;

                case "BLUE":
                    {
                        Color[] cols = { Color.Red, 
                                         Color.Orange,
                                         Color.Yellow, 
                                         Color.LightGreen, 
                                         Color.Blue ,
                                         Color.DarkSalmon,                              
                                         Color.LightPink };

                        for (int j = 0; j < NumGraphs; j++)
                        {
                            display2.DataSources[j].GraphColor = cols[j % 7];
                        }

                        display2.BackgroundColorTop = Color.Navy;
                        display2.BackgroundColorBot = Color.FromArgb(0, 0, 64);
                        display2.SolidGridColor = Color.Blue;
                        display2.DashedGridColor = Color.Blue;
                    }
                    break;

                case "GRAY":
                    {
                        Color[] cols = { Color.DarkRed, 
                                         Color.DarkSlateGray,
                                         Color.DarkCyan, 
                                         Color.DarkGreen, 
                                         Color.DarkBlue ,
                                         Color.DarkMagenta,                              
                                         Color.DeepPink };

                        for (int j = 0; j < NumGraphs; j++)
                        {
                            display2.DataSources[j].GraphColor = cols[j % 7];
                        }

                        display2.BackgroundColorTop = Color.White;
                        display2.BackgroundColorBot = Color.LightGray;
                        display2.SolidGridColor = Color.LightGray;
                        display2.DashedGridColor = Color.LightGray;
                    }
                    break;

                case "RED":
                    {
                        Color[] cols = { Color.DarkCyan, 
                                         Color.Yellow,
                                         Color.DarkCyan, 
                                         Color.DarkGreen, 
                                         Color.DarkBlue ,
                                         Color.DarkMagenta,                              
                                         Color.DeepPink };

                        for (int j = 0; j < NumGraphs; j++)
                        {
                            display2.DataSources[j].GraphColor = cols[j % 7];
                        }

                        display2.BackgroundColorTop = Color.DarkRed;
                        display2.BackgroundColorBot = Color.Black;
                        display2.SolidGridColor = Color.Red;
                        display2.DashedGridColor = Color.Red;
                    }
                    break;

                case "LIGHT_BLUE":
                    {
                        Color[] cols = { Color.DarkRed, 
                                         Color.DarkSlateGray,
                                         Color.DarkCyan, 
                                         Color.DarkGreen, 
                                         Color.DarkBlue ,
                                         Color.DarkMagenta,                              
                                         Color.DeepPink };

                        for (int j = 0; j < NumGraphs; j++)
                        {
                            display2.DataSources[j].GraphColor = cols[j % 7];
                        }

                        display2.BackgroundColorTop = Color.White;
                        display2.BackgroundColorBot = Color.FromArgb(183, 183, 255);
                        display2.SolidGridColor = Color.Blue;
                        display2.DashedGridColor = Color.Blue;
                    }
                    break;

                case "BLACK":
                    {
                        Color[] cols = { Color.FromArgb(255,0,0), 
                                         Color.FromArgb(0,255,0),
                                         Color.FromArgb(255,255,0), 
                                         Color.FromArgb(64,64,255), 
                                         Color.FromArgb(0,255,255) ,
                                         Color.FromArgb(255,0,255),                              
                                         Color.FromArgb(255,128,0) };

                        for (int j = 0; j < NumGraphs; j++)
                        {
                            display2.DataSources[j].GraphColor = cols[j % 7];
                        }

                        display2.BackgroundColorTop = Color.Black;
                        display2.BackgroundColorBot = Color.Black;
                        display2.SolidGridColor = Color.DarkGray;
                        display2.DashedGridColor = Color.DarkGray;
                    }
                    break;
            }

        }

        public void CalcDataGraphs()
        {

            this.SuspendLayout();

            display2.DataSources.Clear();
            display2.SetDisplayRangeX(0, 500);

            string[] nameGraph = { "Acc. X", "Acc. Y", "Acc. Z", "Gyro X", "Gyro Y", "Gyro Z" };

            for (int j = 0; j < NumGraphs; j++)
            {
                display2.DataSources.Add(new DataSource());
                display2.DataSources[j].Name = nameGraph[graphSelected];
                //display2.DataSources[j].OnRenderXAxisLabel += RenderXLabel;


                //this.Text = "ECG Monitor V0.001";
                display2.PanelLayout = PlotterGraphPaneEx.LayoutMode.TILES_HOR;
                //display.DataSources[j].Length = 402;
                display2.DataSources[j].Length = 500;
                display2.DataSources[j].AutoScaleY = false;
                display2.DataSources[j].AutoScaleX = true;
                display2.DataSources[j].SetDisplayRangeY(ymin, ymax);
                //display.DataSources[j].SetGridDistanceY((float)0.5);
                display2.DataSources[j].XAutoScaleOffset = 0;
                CalcSinusFunction_3(display2.DataSources[j], j, 0);
                //display.DataSources[j].OnRenderYAxisLabel = RenderYLabel;

            }
            ApplyColorSchema();

            this.ResumeLayout();
            display2.Refresh();

        }

        private String RenderXLabel(DataSource s, int idx)
        {
            if (s.AutoScaleX)
            {
                //if (idx % 2 == 0)
                {
                    int Value = (int)(s.Samples[idx].x);
                    return "" + Value;
                }
                return "";
            }
            else
            {
                int Value = (int)(s.Samples[idx].x / 240);
                String Label = "" + Value + "\"";
                return Label;
            }
        }

        private String RenderYLabel(DataSource s, float value)
        {
            return String.Format("{0:0}", value);
        }

        private void Form3_FormClosing(object sender, FormClosingEventArgs e)
        {
            mTimer.Stop();
            mTimer.Dispose();
            base.OnClosed(e);
        }

        private void btnZoomIn_Click(object sender, EventArgs e)
        {
            ymin += (float)0.1;
            if (ymin >= 5)
            {
                ymin = -5f;
            }
            ymax -= (float)0.1;
            if (ymax <= -5)
            {
                ymax = 5f;
            }

            if (ymin > ymax)
            {
                ymin = ymax;
            }

            this.Invoke(new EventHandler(animatedGraphDemoToolStripMenuItem_Click));
        }

        private void btnZoomOut_Click(object sender, EventArgs e)
        {
            ymin -= (float)0.1;
            if (ymin <= -5)
            {
                ymin = -5f;
            }
            ymax += (float)0.1;
            if (ymax >= 5)
            {
                ymax = 5f;
            }
            this.Invoke(new EventHandler(animatedGraphDemoToolStripMenuItem_Click));
        }

        private void btnZoonDefault_Click(object sender, EventArgs e)
        {
            ymin = -1.5f;
            ymax = 1.5f;
            this.Invoke(new EventHandler(animatedGraphDemoToolStripMenuItem_Click));
        }

        private void animatedGraphDemoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CurExample = "ANIMATED_AUTO";
            CalcDataGraphs();
        }

        private void cbGraphNum_SelectedValueChanged(object sender, EventArgs e)
        {
            graphSelected = int.Parse(cbGraphNum.SelectedIndex.ToString());
            CalcDataGraphs();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            mTimer.Stop();
            Thread.Sleep(100);
            base.OnClosed(e);
            this.Close();
        }
    } 

}
